<template>
  <div style="padding-bottom: 1rem">
    <div class="top">
      <div class="info display-flex justify-content-flex-justify align-items-center">
        <div class="back display-flex align-items-center justify-content-flex-center">
          <x-icon @click.stop="goBack" type="ios-arrow-left" size="25"></x-icon>
        </div>
        <p class="title" style="margin-right: 20px">{{shopInfo.name}}</p>
        <div class="display-flex justify-content-flex-justify align-items-center">
          <button
            class="display-flex flex-direction-row align-items-center justify-content-flex-center"
            @click="goShopInfo"
            style="margin-right: 8px"
          >联系商家</button>
          <div
            v-show="showShareBtn"
            class="storeHeadR display-flex flex-direction-row align-items-center justify-content-flex-justify"
          >
            <img @click="showPopover" src="@/assets/img/cart/add.png" alt />
            <div v-show="popover" class="popover display-flex flex-direction-column">
              <div @click="shareLink" class="display-flex flex-direction-row align-items-center">
                <img style="margin: 0 .4rem;" src="@/assets/img/cart/shareLink.png" alt />
                <p>店铺链接</p>
              </div>
              <div @click="shareQR" class="display-flex flex-direction-row align-items-center">
                <img style="margin: 0 .4rem;" src="@/assets/img/cart/QRCode.png" alt />
                <p style="border-bottom: 1px solid #ffffff">店铺二维码</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div ref="container" class="container" @scroll="onContainerScroll">
      <swiper v-model="pic_index" dots-position="center" :auto="true">
        <swiper-item class="swiper-demo-img" v-for="(item, index) in carouselImage" :key="item.id">
          <img class="swiper-image" :src="item.imageUrl" @click.stop="toPath(index)" />
        </swiper-item>
      </swiper>
      <div class="notice display-flex align-items-center" v-if="shopInfo.notice">
        <img src="@/assets/img/customer/tongzhi.png" class="icon" alt />
        <span class="text" @click="noticeDialog=true">{{shopInfo.notice}}</span>
        <x-dialog
          v-model="noticeDialog"
          hide-on-blur
          :dialog-style="{maxHeight: '60vh', top: '15%!important'}"
        >
          <div class="noticeBox">
            <div class="noticeBox--title">店铺公告</div>
            {{shopInfo.notice}}
          </div>
        </x-dialog>
      </div>
      <div class="classify">
        <div
          class="item"
          v-for="(item, index) in goodsCategoryImage.rowList"
          :key="item.id"
          @click.stop="toClassify(index)"
        >
          <div class="wrap">
            <img :src="`${item.url}?v=${new Date().getTime()}`" alt />
          </div>
          <p class="title">{{item.name}}</p>
        </div>
      </div>

      <template v-if="activityList.length > 0">
        <h1 class="title">活动专区</h1>
        <ul class="list">
          <li
            class="item"
            v-for="(item, index) in activityList"
            :key="item.id"
            @click.stop="toGoods(item.id)"
          >
            <!--<img src="@/assets/img/customer/icon-tag1.png" class="icon" alt="">
            <img src="@/assets/img/customer/icon-tag2.png" class="icon" alt="">-->
            <div class="noStorageBox">
              <img :src="item.defaultPhoto" class="thumb" alt />
              <div v-if="item.goodsStock<=0" class="noStorage">
                <span>补货中</span>
              </div>
              <ul v-show="item.activityGoodsList" class="display-flex flex-direction-row">
                <li
                  v-for="(a,aIndex) in deWeight(item.activityGoodsList)"
                  :key="aIndex"
                >{{a.type==1?'特价':'搭赠'}}</li>
              </ul>
            </div>
            <p class="title">[{{item.brandName}}]{{item.name}}</p>
            <div
              class="display-flex justify-content-flex-justify"
              v-for="(j,childJIndex) in item.unitVOList"
              :key="childJIndex"
            >
              <p
                class="price"
              >{{j.unitGoodsPricesVO && item.enquiry!=1?'￥'+(j.unitGoodsPricesVO.discountTaxPrice?j.unitGoodsPricesVO.discountTaxPrice:j.unitGoodsPricesVO.taxPrice):'询价'}}</p>
              <!--<p class="specs">/{{j.unitGoodsPricesVO?j.unitGoodsPricesVO.unitName:''}}</p>-->
              <p class="specs">{{j.name}}</p>
            </div>
          </li>
          <li class="loadMore" @click="getActivityList">{{isActivityOver?"没有更多数据了~":"查看更多"}}</li>
        </ul>
      </template>

      <template v-if="recommendList.length > 0">
        <h1 class="title">推荐购买</h1>
        <ul class="list">
          <li
            class="item"
            v-for="(item, index) in recommendList"
            :key="item.id"
            @click.stop="toGoods(item.id)"
          >
            <!--<img src="@/assets/img/customer/icon-tag1.png" class="icon" alt="">
            <img src="@/assets/img/customer/icon-tag2.png" class="icon" alt="">-->
            <div class="noStorageBox">
              <img :src="item.defaultPhoto" class="thumb" alt />
              <div v-if="item.goodsStock<=0" class="noStorage">补货中</div>
            </div>
            <p class="title">[{{item.brandName}}]{{item.name}}</p>
            <div
              class="display-flex justify-content-flex-justify"
              v-for="(j,childJIndex) in item.unitVOList"
              :key="childJIndex"
            >
              <p
                class="price"
              >{{j.unitGoodsPricesVO && item.enquiry!=1?'￥'+(j.unitGoodsPricesVO.discountTaxPrice?j.unitGoodsPricesVO.discountTaxPrice:j.unitGoodsPricesVO.taxPrice):'询价'}}</p>
              <!--<p class="specs">/{{j.unitGoodsPricesVO?j.unitGoodsPricesVO.unitName:''}}</p>-->
              <p class="specs">{{j.name}}</p>
            </div>
          </li>
        </ul>
      </template>
    </div>
  </div>
</template>

<script>
import { Storage } from "@/service/storage";
export default {
  name: "index_keepAlive",
  data() {
    return {
      shopId: "",
      linkURL: "",
      noticeDialog: false,
      showShareBtn: false,
      popover: false,
      shopInfo: {},
      pageNum: 1,
      isLoading: false,
      isOver: false,
      activityPage: 1,
      isActivityOver: false,
      isActivityLoading: false,
      carouselImage: [],
      goodsCategoryImage: [],
      pic_index: 1,
      recommendList: [], // type3
      activityList: [], // type2
    };
  },
  mounted() {
    // setTimeout(()=>{
    //   navigator.vibrate = navigator.vibrate || navigator.webkitVibrate || navigator.mozVibrate || navigator.msVibrate;
    //   if(navigator.vibrate) {
    //     alert("支持设备震动！");
    //   } else {
    //     alert('buzhichi')
    //   }
    // },1000)
    
  },
  beforeDestroy() {
    window["onBackPressed"] = this.oldOnBackPressed;
    this.$callJava({ onBackPressed: false });
  },
  activated() {
    if(!this.shopId || this.shopId!=this.$route.query.id){
      this.init()
    } else {
      this.scrollTop = sessionStorage.getItem("goodsIndexScrollTop") || 0;
      this.$nextTick(() => {
        this.$refs.container.scrollTop = this.scrollTop;
      });
    }
    this.$callJava({ onBackPressed: true });
    this.oldOnBackPressed = window["onBackPressed"];
    window["onBackPressed"] = this.goBack.bind(this);
  },
  deactivated() {
    sessionStorage.setItem("goodsIndexScrollTop", this.scrollTop);
    window["onBackPressed"] = this.oldOnBackPressed;
    this.$callJava({ onBackPressed: false });
  },
  methods: {
    init() {
      if (this.$fromApp(this)) {
        this.showShareBtn = true;
      } else {
        this.showShareBtn = false;
        Storage.set("sellerId", this.$route.query.id);
      }
      var distributorId =
        `${this.$route.query.id}` == "undefined" ? "" : this.$route.query.id;
      // console.log(distributorId)
      this.$ajax.get(
        "carouselImage/list",
        (res) => {
          // 轮播图
          // console.log(res);
          if (res.code == 200) {
            this.carouselImage = res.data;
          }
        },
        { distributorId, pageNo: 1, pageSize: 10 }
      );

      this.$ajax.get(
        "replenish/goodsCategoryImage/list",
        (res) => {
          // 商品分类
          // console.log(res);
          if (res.code == 200) {
            this.goodsCategoryImage = res.data;
          }
        },
        { distributorId, pageNo: 1, pageSize: 10 }
      );

      //获取经销商信息
      this.$ajax.get(
        "common/distributor/info",
        (res) => {
          if (res.code == "200" && res.data) {
            this.shopInfo = res.data;
            this.shareInit();
            // this.shopZeroSaleState = res.data.zeroSaleFlag
          }
        },
        { distributorId: this.$route.query.id }
      );
      this.linkURL =
        this.$webUrl +
        "purchase/storePage?isQrShare=1&id=" +
        this.$route.query.id;
      this.shopId = this.$route.query.id;
      this.initActivityList();
      this.getActivityList();
      this.initRecommendList();
      this.getRecommendList();
    },
    onContainerScroll(e) {
      let ele = e.target;
      var scrollTop = ele.scrollTop;
      this.scrollTop = scrollTop;
      if (this.isLoading || this.isOver) return;
      var clientHeight = ele.clientHeight;
      var scrollHeight = ele.scrollHeight;
      if (
        scrollHeight > clientHeight &&
        scrollHeight - (scrollTop + clientHeight) <= 50
      ) {
        this.getRecommendList();
      }
    },
    deWeight(arr) {
      //对象数组去重
      if (arr == "" || arr == null) {
        arr = [];
      }
      const res = new Map();
      return arr.filter((a) => !res.has(a.type) && res.set(a.type, 1));
    },
    goBack() {
      // this.$callJava({code:1007})
      // this.$router.go(-1);
      if (this.$fromApp(this)) {
        if (this.$route.query.fromPush) {
          this.$callJava({ code: 1007 });
        } else {
          this.$router.go(-1);
        }
      } else {
        this.$router.go(-1);
      }
    },
    goShopInfo() {
      if (Storage.get("token")) {
        if (this.$fromApp(this)) {
          // this.$router.push({path:'/shop/info',query:{shopId:this.shopId,from:'app'}})
          this.$callJava({
            url: this.$webUrl + "shop/info?from=app&shopId=" + this.shopId,
            title: "店铺详情",
          });
        } else {
          this.$router.push({
            path: "/shop/info",
            query: { shopId: this.shopId },
          });
        }
      }
    },
    shareQR() {
      this.popover = !this.popover;
      this.shopInfo.linkUrl = this.linkURL;
      this.$callJava({
        code: 1008,
        shopName: this.shopInfo.name,
        shareLink: this.linkURL,
        shopLogo: this.shopInfo.logo,
      });
    },
    shareLink() {
      this.popover = !this.popover;
      this.shopInfo.linkUrl = this.linkURL;
      this.$callJava({
        code: 1009,
        shopName: this.shopInfo.name,
        shareLink: this.linkURL,
        shopLogo: this.shopInfo.logo,
      });
    },
    showPopover() {
      this.popover = !this.popover;
    },
    callUser() {
      // 联系商家
      if (Storage.get("token")) {
        if (this.$fromApp(this)) {
          this.$callJava({ code: 1001, phone: this.shopInfo.phone });
        } else {
          window.location.href = "tel:" + this.shopInfo.phone;
        }
      }
    },
    vibrate() {
      // navigator.vibrate(1000);
      navigator.vibrate([3000, 2000, 1000, 1000, 3000]);
    },
    initActivityList(){
      this.activityPage = 1;
      this.isActivityOver = false;
      this.isActivityLoading = false;
      this.activityList = [];
    },
    getActivityList() {
      if (this.isActivityOver || this.isActivityLoading) return;
      this.isActivityLoading = true;
      var sellerId =
        `${this.$route.query.id}` == "undefined" ? "" : this.$route.query.id;
      let params = {
        orderType: 2,
        sellerId,
        pageNo: this.activityPage++,
        pageSize: 9,
      };
      this.$ajax.get(
        "replenish/search_goods/list",
        (res) => {
          let list = res.data;
          if (list.length <= 0) {
            this.isActivityOver = true;
          } else {
            this.activityList = this.activityList.concat(list);
          }
          this.isActivityLoading = false;
        },
        params
      );
    },
    initRecommendList() {
      this.pageNum = 1;
      this.isLoading = false;
      this.isOver = false;
      this.recommendList = [];
    },
    getRecommendList() {
      if (this.isLoading || this.isOver) return;
      this.isLoading = true;
      var sellerId =
        `${this.$route.query.id}` == "undefined" ? "" : this.$route.query.id;
      let params = {
        orderType: 3,
        sellerId,
        pageNo: this.pageNum++,
        pageSize: 9,
      };
      this.$ajax.get(
        "replenish/search_goods/list",
        (res) => {
          let list = res.data;
          if (!list || !list.length) {
            this.isOver = true;
          } else {
            this.recommendList = this.recommendList.concat(list);
          }
          this.isLoading = false;
        },
        params
      );
    },
    toPath(index) {
      // 轮播图跳转路径
      var carouselImage = this.carouselImage;
      console.log(carouselImage[index]);
      // window.location.href = carouselImage[index]['linkUrl']
      if (!carouselImage[index]["linkUrl"]) return;
      this.$callJava({
        url: carouselImage[index]["linkUrl"],
        theme: 1,
      });
    },
    toClassify(index) {
      // 点击分类
      var list = this.goodsCategoryImage.rowList;
      console.log(list[index].goodsCategoryId);
      sessionStorage.cate_id = list[index].goodsCategoryId;
      this.$router.push({
        path: "purchase/storePage",
        query: {
          from: "app",
          id: list[index]["distributorId"],
          zeroSaleState: list[index]["zeroSaleFlag"],
          fromManage: 1,
        },
      });
    },
    isIos() {
      const u = navigator.userAgent;
      return u.indexOf("iPhone") > -1 || u.indexOf("Mac OS") > -1;
    },
    shareInit() {
      let _this = this;
      let url = "";
      if (this.isIos()) {
        url = window.location.href;
        url = url.split("#");
        url = url[0];
      } else {
        url = window.location.href;
      }

      let options = {
        url: url,
      };

      this.$ajax.post("wechat/signature/jsapi", options, (res) => {
        wx.config({
          debug: false,
          appId: res.data.appId,
          timestamp: res.data.timestamp,
          nonceStr: res.data.nonceStr,
          signature: res.data.signature,
          jsApiList: [
            "checkJsApi",
            "onMenuShareTimeline",
            "onMenuShareAppMessage",
          ],
        });

        wx.ready(function () {
          wx.onMenuShareTimeline({
            title: `${_this.shopInfo.name}`, // 分享标题
            link:
              _this.$webUrl +
              "purchase/storePage?isQrShare=1&id=" +
              _this.shopId,
            imgUrl: _this.shopInfo.logo || "", // 分享图标
            success: function () {
              // 用户确认分享后执行的回调函数
            },
            cancel: function () {
              // 用户取消分享后执行的回调函数
            },
          });
          wx.onMenuShareAppMessage({
            title: `${_this.shopInfo.name}`,
            desc: "这家店实在是太棒了!", // 分享描述
            link:
              _this.$webUrl +
              "purchase/storePage?isQrShare=1&id=" +
              _this.shopId,
            imgUrl: _this.shopInfo.logo || "",
            success: function () {
              // 用户确认分享后执行的回调函数
            },
            cancel: function () {
              // 用户取消分享后执行的回调函数
            },
          });
        });
      });
    },
    toGoods(id) {
      this.$router.push({
        path: "/good/operate",
        query: { goodId: id, from: this.$fromApp(this) ? "app" : "" },
      });
      // this.$router.push({path: '/good/detail', query: {id: id, type: 1}})
    },
  },
};
</script>

<style scoped type="text/less"  lang="less">
.back {
  position: absolute;
  width: 0.6rem;
  height: 0.6rem;
  padding: 0.05rem;
  border-radius: 100%;
  background: rgba(0, 0, 0, 0.4);
  top: 0.3rem;
  left: 0.3rem;
  z-index: 99;

  svg {
    fill: #fff;
  }
}
.storeHeadR {
  position: relative;

  img {
    width: 0.48rem;
    height: 0.48rem;
  }

  .popover {
    position: absolute;
    padding: 0.15rem 0;
    left: -2.5rem;
    bottom: -1.7rem;
    width: 3rem;
    /*height: 2.02rem;*/
    background-color: #000000;
    border-radius: 0.08rem;
    opacity: 0.7;
    color: #ffffff;
    z-index: 10000;
    > div {
      padding: 0.1rem 0;
    }
    img {
      width: 0.4rem;
      height: 0.4rem;
    }
  }
}
.swiper-image {
  width: 100%;
  height: 100%;
}
.top {
  padding: 0.3rem;
}
.info {
  padding: 0.3rem 0;
  .title {
    color: #333333;
    font-size: 0.36rem;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  button {
    color: #ffffff;
    font-size: 0.24rem;
    width: 1.34rem;
    height: 0.38rem;
    background: #517dd9;
    border-radius: 0.2rem;
    text-align: center;
    // line-height: .38rem;
    border: none;
  }
}
.container {
  padding: 0 0.2rem 0.5rem;
  position: absolute;
  bottom: 1rem;
  width: 100%;
  top: 1.5rem;
  box-sizing: border-box;
  overflow-y: auto;
}
h1.title {
  font-size: 0.32rem;
  color: #333333;
  font-weight: bold;
  position: relative;
  padding: 0.3rem 0 0.3rem 0.3rem;
  &::before {
    content: "";
    width: 0.1rem;
    height: 0.28rem;
    background: #517dd9;
    position: absolute;
    left: 0;
    top: 0;
    margin: auto;
    bottom: 0;
  }
}
.classify {
  width: 7.1rem;
  height: 1.8rem;
  background: #ffffff;
  border-radius: 0.12rem;
  padding: 0.15rem 0.21rem;
  margin: auto;
  box-sizing: border-box;
  overflow: hidden;
  overflow-x: auto;
  -webkit-overflow-scrolling: touch;
  white-space: nowrap;
  .item {
    width: 1.12rem;
    text-align: center;
    display: inline-block;
    &:not(:last-child) {
      margin-right: 0.32rem;
    }
  }
  .wrap {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 1.12rem;
    height: 1.12rem;
  }
  img {
    width: 100%;
    height: auto;
  }
  .title {
    font-size: 0.26rem;
    color: #333333;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
}
.notice {
  margin-top: 0.3rem;
  font-size: 0.28rem;
  .icon {
    width: 0.4rem;
    height: 0.32rem;
    margin-right: 0.2rem;
  }
  .text {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    min-width: 0;
  }
}
ul.list {
  width: 7.1rem;
  background: #ffffff;
  border-radius: 0.08rem;
  padding: 0.18rem 0.22rem;
  box-sizing: border-box;
  .item {
    width: 2.08rem;
    list-style: none;
    position: relative;
    display: inline-block;
    margin-bottom: 0.2rem;
    vertical-align: text-top;
    &:not(:nth-child(3n)) {
      margin-right: 0.2rem;
    }
  }
  .thumb {
    width: 2.08rem;
    height: 2.08rem;
    border-radius: 0.08rem;
  }
  .icon {
    width: 0.9rem;
    height: 0.56rem;
    position: absolute;
    top: 0;
    left: -0.1rem;
  }
  .title {
    margin: 0.08rem auto;
    font-size: 0.26rem;
    color: #333333;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
  .price {
    color: #f13e3e;
    font-size: 0.26rem;
  }
  .specs {
    font-size: 0.24rem;
    color: #8d919e;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
}
.noticeBox {
  max-height: 60vh;
  overflow-y: auto;
  padding: 0.2rem;
}
.noticeBox--title {
  text-align: center;
  font-size: 0.32rem;
  font-weight: bold;
}
.noStorageBox {
  position: relative;
  ul {
    position: absolute;
    top: 0;
    left: 0;
    li {
      margin-right: 0.1rem;
      color: #ffffff;
      font-size: 12px;
      background-color: #fc6e51;
      padding: 0.03rem 0.08rem;
    }
  }
}
.noStorage {
  position: absolute;
  top: 0;
  left: 0;
  width: 2.08rem;
  height: 2.08rem;
  background-color: rgba(0, 0, 0, 0.4);
  color: white;
  // line-height: 2.08rem;
  // text-align: center;
  font-size: 0.32rem;
  display: flex;
  align-items: center;
  justify-content: center;
}
.loadMore {
  list-style: none;
  text-align: center;
}
</style>
